import { defineStore, createPinia } from 'pinia'
import main from "../main";//main.ts文件中要暴露app
import JSONBIG from 'json-bigint';

const store = createPinia()
import piniaPluginpersistedstate from 'pinia-plugin-persist'
store.use(piniaPluginpersistedstate)

// useMain  可以是 useUser、useCart 之类的名字 
// defineStore('main',{..}) 在devtools 就使用 main 这个名
const useMain = defineStore('main', {
    // 相当于data
    state: () => {
        return {
            authToken: sessionStorage.getItem("authToken") ? sessionStorage.getItem("authToken") : "",//token
            refreshToken: sessionStorage.getItem("refreshToken") ? sessionStorage.getItem("refreshToken") : "",//刷新接口token
            userInfo: sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")!) : {},//用户信息
            showSpread: sessionStorage.getItem("showSpread") ? JSON.parse(sessionStorage.getItem("showSpread")!) : true,//左侧菜单栏是否展开
            userProjectRsps: sessionStorage.getItem("userProjectRsps") ? JSON.parse(sessionStorage.getItem("userProjectRsps")!) : [],//项目信息
            currentProjectInfo: sessionStorage.getItem("currentProjectInfo") ? JSON.parse(sessionStorage.getItem("currentProjectInfo")!) : {},//当前项目信息
            menuListInfo: sessionStorage.getItem("menuListInfo") ? JSON.parse(sessionStorage.getItem("menuListInfo")!) : [] as Array<any>,//左侧菜单栏信息
            platformInfo: sessionStorage.getItem("platformInfo") ? JSON.parse(sessionStorage.getItem("platformInfo")!) : [] as Array<any>,//平台信息
            countDown: sessionStorage.getItem("countDown") ? JSON.parse(sessionStorage.getItem("countDown")!) : 0,//忘记页面-倒计时
            msgNum: sessionStorage.getItem("msgNum") ? JSON.parse(sessionStorage.getItem("msgNum")!) : 0,//顶部栏消息数
            topics: sessionStorage.getItem("topics") ? JSON.parse(sessionStorage.getItem("topics")!) : [],//订阅话题
            topics2: sessionStorage.getItem("topics2") ? JSON.parse(sessionStorage.getItem("topics2")!) : [],//订阅话题
            msgList: sessionStorage.getItem("msgList") ? JSON.parse(sessionStorage.getItem("msgList")!) : [],//实时消息列表
            showDrawer: sessionStorage.getItem("showDrawer") ? JSON.parse(sessionStorage.getItem("showDrawer")!) : false,//是否展示全局消息弹窗
            needUpdate: sessionStorage.getItem("needUpdate") ? JSON.parse(sessionStorage.getItem("needUpdate")!) : false,//message页面是否要更新数据
            messageType: sessionStorage.getItem("messageType") ? sessionStorage.getItem("messageType") : '1',//message页面是否报警消息点击查看
            packUp_alarmReception: sessionStorage.getItem("packUp_alarmReception") ? JSON.parse(sessionStorage.getItem("packUp_alarmReception")!) : true,//报警接收,搜索栏是否收起
            packUp_alarmRule: sessionStorage.getItem("packUp_alarmRule") ? JSON.parse(sessionStorage.getItem("packUp_alarmRule")!) : true,//报警规则,搜索栏是否收起
            packUp_eq_searchBar: sessionStorage.getItem("packUp_eq_searchBar") ? JSON.parse(sessionStorage.getItem("packUp_eq_searchBar")!) : true,//设备运维,搜索栏是否收起
            packUp_al_searchBar: sessionStorage.getItem("packUp_al_searchBar") ? JSON.parse(sessionStorage.getItem("packUp_al_searchBar")!) : true,//资产列表,搜索栏是否收起
            packUp_stationManage: sessionStorage.getItem("packUp_stationManage") ? JSON.parse(sessionStorage.getItem("packUp_stationManage")!) : true,//工位管理,搜索栏是否收起
            packUp_modelCom: sessionStorage.getItem("packUp_modelCom") ? JSON.parse(sessionStorage.getItem("packUp_modelCom")!) : true,//变更记录模型,搜索栏是否收起
            packUp_overhaul: sessionStorage.getItem("packUp_overhaul") ? JSON.parse(sessionStorage.getItem("packUp_overhaul")!) : true,//检修报修,搜索栏是否收起
            judgmentName: sessionStorage.getItem("judgmentName") ? JSON.parse(sessionStorage.getItem("judgmentName")!) : '资产',
            assetListName: sessionStorage.getItem("assetListName") ? JSON.parse(sessionStorage.getItem("assetListName")!) : '资产管理',
            environmentInfo: sessionStorage.getItem("environmentInfo") ? JSON.parse(sessionStorage.getItem("environmentInfo")!) : '',//当前环境信息 sjs深交所
        }
    },
    // 相当于计算属性
    getters: {
    },
    // 相当于vuex的 mutation + action，可以同时写同步和异步的代码
    actions: {
        updatedAuthToken(value: any) {
            sessionStorage.setItem("authToken", value);
            this.authToken = value;
        },
        updatedRefreshToken(value: any) {
            sessionStorage.setItem("refreshToken", value);
            this.refreshToken = value;
        },
        updatedUserInfo(value: {}) {
            sessionStorage.setItem("userInfo", JSON.stringify(value));
            this.userInfo = value;
        },
        updatedShowSpread(value: boolean) {
            sessionStorage.setItem("showSpread", JSON.stringify(value));
            this.showSpread = value;
        },
        updatedUserProjectRsps(value: []) {
            sessionStorage.setItem("userProjectRsps", JSON.stringify(value));
            this.userProjectRsps = value;
        },
        updatedMenuListInfo(value: []) {
            sessionStorage.setItem("menuListInfo", JSON.stringify(value));
            this.menuListInfo = value;
        },
        updatedPlatformInfo(value: []) {
            sessionStorage.setItem("platformInfo", JSON.stringify(value));
            this.platformInfo = value;
        },
        updatedCountDown(value: number) {
            sessionStorage.setItem("countDown", JSON.stringify(value));
            this.countDown = value;
        },
        updatedProjectInfo(value: any) {
            sessionStorage.setItem("currentProjectInfo", JSON.stringify(value));
            this.currentProjectInfo = value;
        },
        updatedMsgNum(value: number) {
            sessionStorage.setItem("msgNum", JSON.stringify(value));
            this.msgNum = value;
        },
        updatedTopics(value: any) {
            sessionStorage.setItem("topics", JSON.stringify(value));
            this.topics = value;
        },
        updatedTopics2(value: any) {
            sessionStorage.setItem("topics2", JSON.stringify(value));
            this.topics2 = value;
        },
        updatedMsgList(value: any) {
            sessionStorage.setItem("msgList", JSON.stringify(value));
            this.msgList = value;
        },
        updatedShowDrawer(value: boolean) {
            sessionStorage.setItem("showDrawer", JSON.stringify(value));
            this.showDrawer = value;
        },
        updatedNeedUpdate(value: boolean) {
            sessionStorage.setItem("needUpdate", JSON.stringify(value));
            this.needUpdate = value;
        },
        updatedMessageType(value: string) {
            sessionStorage.setItem("messageType", value);
            this.messageType = value;
        },
        delMsgNum() {
            if (this.msgNum > 0) {
                this.msgNum = this.msgNum - 1;
                sessionStorage.setItem("msgNum", JSON.stringify(this.msgNum));
            }
        },
        updatedpackUpAlarmReception(value: boolean) {
            sessionStorage.setItem("packUp_alarmReception", JSON.stringify(value));
            this.packUp_alarmReception = value;
        },
        updatedPackUpAlarmRule(value: boolean) {
            sessionStorage.setItem("packUp_alarmRule", JSON.stringify(value));
            this.packUp_alarmRule = value;
        },
        updatedpackUpEqSearchBar(value: boolean) {
            sessionStorage.setItem("packUp_eq_searchBar", JSON.stringify(value));
            this.packUp_eq_searchBar = value;
        },
        updatedpackUpAlSearchBar(value: boolean) {
            sessionStorage.setItem("packUp_al_searchBar", JSON.stringify(value));
            this.packUp_al_searchBar = value;
        },
        updatedpackUpStationManage(value: boolean) {
            sessionStorage.setItem("packUp_stationManage", JSON.stringify(value));
            this.packUp_stationManage = value;
        },
        updatedpackUpModelCom(value: boolean) {
            sessionStorage.setItem("packUp_modelCom", JSON.stringify(value));
            this.packUp_modelCom = value;
        },
        updatedpackUpOverhaul(value: boolean) {
            sessionStorage.setItem("packUp_overhaul", JSON.stringify(value));
            this.packUp_overhaul = value;
        },
        updatedEnvironmentInfo(value: boolean) {
            sessionStorage.setItem("environmentInfo", JSON.stringify(value));
            this.environmentInfo = value;
        },
        mqtt_service() {//开启mqtt服务
            // this.msgList = [];
            // mqtt连接成功
            main.config.globalProperties.$mqtt.on('connect', (e: any) => {
                // console.log('连接成功:', e)
                // console.log(state.topics)
                main.config.globalProperties.$mqtt.subscribe(this.topics, { qos: 1 }, (error: any) => {
                    if (!error) {
                        console.log('订阅成功', this.topics)
                    } else {
                        console.log('订阅失败')
                    }
                })
                main.config.globalProperties.$mqtt.subscribe(this.topics2, { qos: 1 }, (error: any) => {
                    if (!error) {
                        console.log('订阅成功', this.topics2)
                    } else {
                        console.log('订阅失败')
                    }
                })
            })

            // 接收消息处理
            main.config.globalProperties.$mqtt.on('message', (topic: any, message: any) => {
                console.log('收到来自', topic, '的消息', message.toString())
                // const msg = JSON.parse(message.toString());
                const msg = JSONBIG.parse(message.toString());

                if (msg) {
                    // this.msgList.push(msg);
                    this.msgList.unshift(msg);
                    sessionStorage.setItem("msgList", JSON.stringify(this.msgList));
                    this.showDrawer = true;//打开全局实时弹窗
                    sessionStorage.setItem("showDrawer", JSON.stringify(true));
                    this.msgNum = this.msgNum + 1;//顶部消息数+1
                    sessionStorage.setItem("msgNum", JSON.stringify(this.msgNum));


                    if (msg.msgType == 1 && window.location.href.indexOf('/message') > -1) {
                        this.needUpdate = true;
                        sessionStorage.setItem("needUpdate", JSON.stringify(true));
                    }
                }
            })
            // 断开发起重连
            main.config.globalProperties.$mqtt.on('reconnect', (error: any) => {
                console.log('正在重连:', error)
            })
            // 链接异常处理
            main.config.globalProperties.$mqtt.on('error', (error: any) => {
                console.log('连接失败:', error)
            })
        },
        //断开MQTT
        mqtt_close() {
            // console.log('断开MQTT',main.config.globalProperties.$mqtt);
            if (!main.config.globalProperties.$mqtt) {
                return;
            }
            main.config.globalProperties.$mqtt.unsubscribe(this.topics, (error: any) => {
                if (!error) {
                    console.log(this.topics, '取消订阅成功');
                } else {
                    console.log(this.topics, '取消订阅失败');
                }
            })
            main.config.globalProperties.$mqtt.unsubscribe(this.topics2, (error: any) => {
                if (!error) {
                    console.log(this.topics2, '取消订阅成功');
                } else {
                    console.log(this.topics2, '取消订阅失败');
                }
            })
            main.config.globalProperties.$mqtt.end(true)
        },
        updatejudgmentName(value: string) {
            sessionStorage.setItem("judgmentName", JSON.stringify(value));
            this.judgmentName = value;
        },
        updateassetListName(value: string) {
            sessionStorage.setItem("assetListName", JSON.stringify(value));
            this.assetListName = value;
        }
    },
    // persist:{
    //     enabled:true,
    //     strategies:[{
    //         key:"store",//自定义存储名称
    //         storage:sessionStorage,//自定义存储位置
    //         // storage:localStorage,//自定义存储位置
    //     }]
    // }
})

export { store, useMain }
